import React, { useState } from 'react';
import { useRef } from 'react';
import { EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { Access } from 'umi';
import usePermission from '@/hooks/usePermission';
import { Button, Tooltip, Space, message, Switch, Drawer, Popconfirm } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import request from 'umi-request';
import { changeRoleIsDefault, deleteRole } from '@/services/role';
import RoleItem from './components/item';

const Role: React.FC = () => {
  const [visible, setVisible] = useState<boolean>(false);
  const [roleId, setRoleId] = useState<number | null>();
  const actionRef = useRef<ActionType>();

  const changeDefault = async (record: ROLE_API.Role) => {
    const rsp = await changeRoleIsDefault({ id: record.id });
    if (rsp.code === 0) {
      message.success(`【${record.role_name}】修改为默认角色`);
      actionRef?.current?.reload();
    }
  };

  const toFetchList = () => {
    actionRef?.current?.reload();
  };

  const handleEditRole = async (record: ROLE_API.Role) => {
    setRoleId(record.id);
    setVisible(true);
  };

  const handleDeleteRole = async (record: ROLE_API.Role) => {
    const rsp = await deleteRole({ ids: [record.id] });
    if (rsp.code === 0) {
      message.success('删除成功');
      toFetchList();
    }
  };

  const columns: ProColumns<ROLE_API.Role>[] = [
    {
      title: '角色名称',
      dataIndex: 'role_name',
      fieldProps: { placeholder: '请输入角色名称' },
      ellipsis: true,
      align: 'center',
    },
    {
      title: '创建时间',
      align: 'center',
      dataIndex: 'created_at',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '是否默认角色',
      align: 'center',
      dataIndex: 'is_default',
      hideInSearch: true,
      render: (text, record) => [
        <Switch
          checkedChildren="是"
          unCheckedChildren="否"
          checked={record.is_default === 1}
          onChange={() => changeDefault(record)}
        />,
      ],
    },
    {
      title: '备注',
      align: 'center',
      dataIndex: 'remark',
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      render: (text, record, _, action) => [
        <Space>
          <Access accessible={usePermission('system:role:update')} fallback={null}>
            <Tooltip title="修改">
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => handleEditRole(record)}
            />
          </Tooltip>
          </Access>
          <Access accessible={usePermission('system:role:delete')} fallback={null}>
             <Tooltip title="删除">
            <Popconfirm
              title={`确定删除【${record.role_name}】角色?`}
              onConfirm={() => handleDeleteRole(record)}
              okText="确定"
              cancelText="取消"
            >
              <Button type="primary" danger shape="circle" icon={<DeleteOutlined />} />
            </Popconfirm>
          </Tooltip>
          </Access>
        </Space>,
      ],
    },
  ];

  const fetchList = async (params: {}, sort = {}) => {
    const rsp = await request<{
      data: { list: ROLE_API.Role[]; total: number };
      code: number;
    }>('/api/v1/roles', {
      params,
    });
    if (rsp.code === 0) {
      return {
        data: rsp.data.list,
        total: rsp.data.total,
        success: true,
      };
    }
  };

  const handleAddRole = () => {
    setVisible(true);
  };

  const onClose = () => {
    setVisible(false);
    setRoleId(null);
  };

  return (
    <>
      <ProTable<ROLE_API.Role>
        columns={columns}
        actionRef={actionRef}
        request={fetchList}
        search={{
          span: 6,
        }}
        rowKey="id"
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
        }}
        form={{}}
        dateFormatter="string"
        headerTitle="角色列表"
        toolBarRender={() => [
          <Access accessible={usePermission('system:role:add')} fallback={null}>
            <Button key="button" onClick={handleAddRole} icon={<PlusOutlined />} type="primary">
              新增
            </Button>
          </Access>,
        ]}
      />

      <Drawer
        title={roleId ? '修改角色' : '新增角色'}
        placement="right"
        width={500}
        onClose={onClose}
        visible={visible}
      >
        {visible && <RoleItem onClose={onClose} roleId={roleId} toFetchList={toFetchList} />}
      </Drawer>
    </>
  );
};

export default Role;
